<?php

namespace app\admin\controller\user;

use app\common\controller\Backend;
use app\common\library\Auth;
use app\common\library\IdentityCard;
use app\common\model\Merchant as MerchatModel;
use think\exception\ValidateException;
use think\facade\Db;

/**
 * 会员管理.
 *
 * @icon fa fa-user
 */
class User extends Backend
{
    protected $relationSearch = true;

    protected $searchFields = 'id,username,nickname';
    /**
     * @var \app\admin\model\User
     */
    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\User();
    }

    /**
     * 查看.
     */
    public function index()
    {
        //设置过滤方法
        $this->request->filter(['strip_tags']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            [$where, $sort, $order, $offset, $limit] = $this->buildparams();
            $total = $this->model
                ->with('order')
                ->withJoin('group')
                ->where($where)
                ->order($sort, $order)
                ->count();
            $list  = $this->model
                ->with('order')
                ->withJoin('group')
                ->where($where)
                ->order($sort, $order)
                ->limit($offset, $limit)
                ->select();
//            dump($list->toArray());die;
            foreach ($list as $k => $v) {
                $v->hidden(['password', 'salt']);
                if($v->is_black == 2){
                    $v->black_reason = '身份证号：' . $v->black_idcard . '；拉黑原因：' . $v->black_reason;
                }else{
                    $v->black_reason = '';
                }
                $v->order_num = $v->order->count();
            }
            $result = ['total' => $total, 'rows' => $list];

            return json($result);
        }

        return $this->view->fetch();
    }

    /**
     * 编辑.
     */
    public function edit($ids = null)
    {
        if ($this->request->isPost()) {
            $this->token();
        }
        $row                 = $this->model->get($ids);
        $this->modelValidate = true;
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        $this->view->assign('groupList',
            build_select('row[group_id]', \app\admin\model\UserGroup::column('name', 'id'), $row['group_id'],
                ['class' => 'form-control selectpicker']));

        return parent::edit($ids);
    }

    /**
     * 删除
     */
    public function del($ids = "")
    {
        $row                 = $this->model->get($ids);
        $this->modelValidate = true;
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        Auth::instance()->delete($row['id']);
        $this->success();
    }

    /**
     * 拉黑恢复
     */
    public function black()
    {
        $ids = $this->request->param('ids');
        $type = $this->request->param('type');
        $this->modelValidate = true;
        if (!$ids) {
            $this->error(__('No Results were found'));
        }
        $row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        if($type == 1 && $row['is_black'] == 1){
            $this->error('用户已恢复');
        }
        if($type == 2 && $row['is_black'] == 2){
            $this->error('用户已被拉黑');
        }
        if($this->request->isPost()){
            $params = $this->request->post('row/a');
            if ($type == 2 && !$params) {
                $this->error(__('Parameter %s can not be empty', ''));
            }
            Db::startTrans();
            try {
                if($type == 2){
                    $update = [
                        'is_black' => $type,
                        'black_time' => time(),
                        'black_admin' => $this->admin['id'],
                        'black_idcard' => $params['black_idcard']??'',
                        'black_reason' => $params['black_reason']
                    ];
                }else{
                    $update = [
                        'is_black' => $type,
                        'white_time' => time(),
                        'white_admin' => $this->admin['id'],
                    ];
                }
                $res = $this->model->where('id', $row['id'])->update($update);
                Db::commit();
            } catch (ValidateException $e) {
                Db::rollback();
                $this->error($e->getMessage());
            } catch (\PDOException $e) {
                Db::rollback();
                $this->error($e->getMessage());
            } catch (Exception $e) {
                Db::rollback();
                $this->error($e->getMessage());
            }
            $text = $type == 1 ? '拉黑' : '恢复';
            if ($res){
                $this->success($text.'成功！');
            }else{
                $this->error($text.'失败！');
            }
        }else{
            return $this->view->fetch();
        }

    }

}
